package com.waa.gulimall.auth.Service.impl;

import com.waa.gulimall.auth.Service.AuthServerService;
import com.waa.gulimall.auth.feigin.ThirdPartyFeginService;
import com.waa.gulimall.common.constant.AuthServerConstant;
import com.waa.gulimall.common.exception.BizCodeEnume;
import com.waa.gulimall.common.exception.RRException;
import com.waa.gulimall.common.utils.ProductCheckCode;
import com.waa.gulimall.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class AuthServerServiceImpl implements AuthServerService {
    @Autowired
    private ThirdPartyFeginService thirdPartyFeginService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void sendCode(String emailNumber) {
        //1.接口防刷
        final String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.EMAIL_CODE_CACHE_PREFIX + emailNumber);
        if (redisCode != null) {
            final String sendTime = redisCode.split("_")[1];
            final long parseLong = Long.parseLong(sendTime);
            if (System.currentTimeMillis() - parseLong < 60000) {
                //60秒内不能再发
                throw new RRException(BizCodeEnume.EMAIL_CODE_EXCEPION.getMsg(), BizCodeEnume.EMAIL_CODE_EXCEPION.getCode());
            }
        }
        //获取验证码
        final String checkCode = ProductCheckCode.getCheckCode();
        //2.验证码再次校验，redis存key-email,value-code email:code:**********->****
        //redis缓存验证码 5分钟有效
        stringRedisTemplate.opsForValue().set(AuthServerConstant.EMAIL_CODE_CACHE_PREFIX + emailNumber, checkCode + "_" +
                System.currentTimeMillis(), 5, TimeUnit.MINUTES);
        thirdPartyFeginService.sendEmail(emailNumber, checkCode);
    }
}
